package org.qs.webservice.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.qs.webservice.content.IReadContent;
import org.qs.webservice.dao.content.ConBookMapper;
import org.qs.webservice.dao.content.ConBookStatMapper;
import org.qs.webservice.dao.content.ConChapterMapper;
import org.qs.webservice.dao.user.UsBalanceMapper;
import org.qs.webservice.dao.user.UsBookRecentMapper;
import org.qs.webservice.dao.user.UsBookReviewMapper;
import org.qs.webservice.dao.user.UsBookShelfMapper;
import org.qs.webservice.dao.user.UsConsumeMapper;
import org.qs.webservice.dao.user.UsMemberPointMapper;
import org.qs.webservice.dao.user.UsMemberVotesMapper;
import org.qs.webservice.dao.user.UsSubscribeAutoMapper;
import org.qs.webservice.dao.user.UsSubscribeMapper;
import org.qs.webservice.dao.user.UsUserMapper;
import org.qs.webservice.dao.user.UserGradeMapper;
import org.qs.webservice.domain.ConBook;
import org.qs.webservice.domain.ConBookRelate;
import org.qs.webservice.domain.ConBookStat;
import org.qs.webservice.domain.ConChapter;
import org.qs.webservice.domain.UsBalance;
import org.qs.webservice.domain.UsBookRecent;
import org.qs.webservice.domain.UsBookShelf;
import org.qs.webservice.domain.UsConsume;
import org.qs.webservice.domain.UsMemberPoint;
import org.qs.webservice.domain.UsMemberVotes;
import org.qs.webservice.domain.UsSubscribe;
import org.qs.webservice.domain.UsSubscribeAuto;
import org.qs.webservice.domain.UsUser;
import org.qs.webservice.exception.QSReadException;
import org.qs.webservice.filter.CustomerLog;
import org.qs.webservice.service.BookService;
import org.qs.webservice.service.IreadMemcacheService;
import org.qs.webservice.service.UpdateDataService;
import org.qs.webservice.task.UpdateTask;
import org.qs.webservice.util.DateUtil;
import org.qs.webservice.util.IReadUtils;
import org.qs.webservice.util.IdWorker;
import org.qs.webservice.util.StringUtils;
import org.qs.webservice.vo.Book;
import org.qs.webservice.vo.BookChapter;
import org.qs.webservice.vo.BookRelate;
import org.qs.webservice.vo.BookVol;
import org.qs.webservice.vo.Chapter;
import org.qs.webservice.vo.BookChapterContent;
import org.qs.webservice.vo.Consume;
import org.qs.webservice.vo.PageData;
import org.springframework.stereotype.Service;

@Service
public class BookServiceImpl implements BookService {
	@Resource
	private UsBookReviewMapper usBookReviewMapper;
	@Resource
	private ConBookMapper conBookMapper;
	@Resource
	private ConChapterMapper conChapterMapper;
	@Resource
	private IreadMemcacheService ireadMemcacheService;
	@Resource
	private UsSubscribeAutoMapper usSubscribeAutoMapper;
	@Resource
	private UsUserMapper userMapper;
	@Resource
	private UsBalanceMapper usBalanceMapper;
	@Resource
	private UsSubscribeMapper usSubscribeMapper;
	@Resource
	private UsConsumeMapper usConsumeMapper;
	@Resource
	private UsMemberPointMapper usMemberPointMapper;
	@Resource
	private UpdateDataService updateDataService;
	@Resource
	private ConBookStatMapper conBookStatMapper;
	@Resource
	private UsMemberVotesMapper usMemberVotesMapper;
	@Resource
	private UsBookShelfMapper usBookShelfMapper;
	@Resource
	private UsBookRecentMapper usBookRecentMapper;
	@Resource
	private UserGradeMapper userGradeMapper;
	Logger logger = Logger.getLogger(getClass());
	@Override
	public String getInfo(String book_id,String token) {
		Map<String,Object> tokenMap = new HashMap<String,Object>();
		int book_id_int=0;
		try {
			book_id_int = Integer.valueOf(book_id);
		} catch (NumberFormatException e) {
			tokenMap.put("code", 403);
			tokenMap.put("reason","参数错误");
			return IReadUtils.beanToJson(tokenMap); 
		}
		if(book_id_int==0){
			tokenMap.put("code", 403);
			tokenMap.put("reason","参数错误");
			return IReadUtils.beanToJson(tokenMap); 
		}
		ConBook conBook = conBookMapper.getBookById(book_id_int);
		if(conBook==null){
			tokenMap.put("code", 403);
			tokenMap.put("reason","图书不存在");
			return IReadUtils.beanToJson(tokenMap); 
		}
		if(conBook.getBook_status()==0){
			tokenMap.put("code", 403);
			tokenMap.put("reason","图书已下架");
			return IReadUtils.beanToJson(tokenMap); 
		}
		if(conBook.getBook_status()==2){
			tokenMap.put("code", 403);
			tokenMap.put("reason","图书待上");
			return IReadUtils.beanToJson(tokenMap); 
		}
		if(conBook.getBook_status()==3){
			tokenMap.put("code", 403);
			tokenMap.put("reason","图书已删除");
			return IReadUtils.beanToJson(tokenMap); 
		}
		if(conBook.getBook_status()!=1){
			tokenMap.put("code", 403);
			tokenMap.put("reason","图书状态未知");
			return IReadUtils.beanToJson(tokenMap); 
		}
		Book book = setBookInfo(conBook);
		String user_id = IReadUtils.getUserIdByTokenWithoutEffective(token);
		if(!StringUtils.isNullOrEmpty(user_id)){
			//获取是否自动订购
			UsSubscribeAuto usSubscribeAuto = usSubscribeAutoMapper.getUsSubscribeById(Long.valueOf(user_id),book_id_int);
			if(usSubscribeAuto!=null&&usSubscribeAuto.getStatus()==1){
				book.setSubscribe_auto(1);
			}
			if(user_id.equals(book.getAuthor_id())){
				book.setIs_author(1);
			}
			UsBookShelf usBookShelf = usBookShelfMapper.getShelfByBookIdAndUserId(book_id_int, Long.valueOf(user_id));
			if(usBookShelf!=null){
				book.setCollect_status(1);
			}
			UsBookRecent usBookRecent = usBookRecentMapper.getBookRecentByBookId(book_id_int, Long.valueOf(user_id));
			if(usBookRecent!=null){
				book.setCurrent_chap_id(usBookRecent.getChapter_id());
			}
		}
		
		tokenMap.put("content",book);
		tokenMap.put("code",200);
		return IReadUtils.beanToJson(tokenMap); 
	}
	public Book setBookInfo(ConBook conBook){
		Book book = new Book();
		book.setBook_id(conBook.getBook_id());
		book.setBook_name(conBook.getBook_name());
		book.setImage_url(conBook.getBook_cover());
		book.setBook_synopses(conBook.getBook_synopses());
		if(conBook.getSerial_status()==0){
			book.setSerial_status("连载中");
		}else if(conBook.getSerial_status()==1){
			book.setSerial_status("已完结");
		}else if(conBook.getSerial_status()==2){
			book.setSerial_status("出版中");
		}else if(conBook.getSerial_status()==3){
			book.setSerial_status("暂停");
		}else if(conBook.getSerial_status()==4){
			book.setSerial_status("封笔");
		}else{
			book.setSerial_status("未知");
		}
		book.setVotes(conBook.getVotes());
		book.setSerial_enddate(DateUtil.getString(conBook.getSerial_enddate(), "yyyy-MM-dd"));
		book.setAuthor_id(conBook.getAuthor_id()+"");
		book.setAuthor_name(conBook.getAuthor_name());
		book.setLast_chap_id(conBook.getLast_chap_id());
		book.setFirst_chap_id(conBook.getFirst_chap_id());
		book.setLast_chap_name(conBook.getLast_chap_name());
		book.setLast_chap_date(DateUtil.getString(conBook.getLast_chap_date(), "yyyy-MM-dd HH:mm:ss"));
		book.setWord_size(conBook.getWord_size());
		book.setBook_notice(conBook.getBook_notice());
		book.setBook_status(conBook.getBook_status());
		book.setCategory_name(conBook.getCategory_name());
		book.setCategory_id(conBook.getCategory_id());
		book.setCollect_uv(conBook.getFavorites()+"");
		book.setCreate_time(DateUtil.getString(conBook.getCreate_time(), "yyyy-MM-dd HH:mm:ss"));
		book.setModify_time(DateUtil.getString(conBook.getModify_time(), "yyyy-MM-dd HH:mm:ss"));
		UsUser usUser = userMapper.getCustomUserByUserid(conBook.getAuthor_id());
		book.setAuthor_img_url(IReadContent.default_portrait_url);
		book.setMcp_id(conBook.getMcp_id());
		book.setMcp_name(conBook.getMcp_name());
		book.setRewards(conBook.getRewards());
		if(usUser!=null){
			if(!StringUtils.isNullOrEmpty(usUser.getImage_url())){
				book.setAuthor_img_url(IReadContent.portrait_url+usUser.getImage_url());
			}
		}
		
		book.setC_click(conBook.getC_click());
		//获取作者相关数据
		List<BookRelate> relates = new ArrayList<BookRelate>();
		for(ConBookRelate conBookRelate : conBook.getRelates()){
			BookRelate bookRelate = new BookRelate();
			bookRelate.setBook_id(conBookRelate.getRelate_book_id());
			bookRelate.setBook_name(conBookRelate.getRelate_book_name());
			bookRelate.setImage_url(IReadContent.portrait_url+conBookRelate.getRelate_image_url());
			relates.add(bookRelate);
		}
		book.setRelates(relates);
		return book;
	}
	@Override
	public String getChapters(String book_id,String order,String token,String device_identifier) {
		Map<String,Object> tokenMap = new HashMap<String,Object>();
		int book_id_int=0;
		try {
			
			book_id_int = Integer.valueOf(book_id);
		} catch (NumberFormatException e) {
			book_id_int=0;
		}
		if(book_id_int<=0){
			tokenMap.put("code", 403);
			tokenMap.put("reason","参数错误");
			return IReadUtils.beanToJson(tokenMap); 
		}
		if(StringUtils.isNullOrEmpty(order)){
			order = "asc";
		}else if("desc".equals(order.toLowerCase())){
				order = "desc";
		}
		String user_id = IReadUtils.getUserIdByToken(token, ireadMemcacheService, device_identifier);
		UsSubscribe usSubscribe = null;
		if(StringUtils.isNullOrEmpty(user_id)){
			user_id=null;
		}else{
			//判断是否已订购
			usSubscribe = usSubscribeMapper.getUsSubscribeById(Long.valueOf(user_id), book_id_int,0);
		}
		ConBook conBook = conBookMapper.getBookById(book_id_int);
		//int total = conChapterMapper.getChaptersCountWithoutContent(book_id_int, new Date());
		//tokenMap.put("total", total);
		List<ConChapter> list = conChapterMapper.getChaptersWithoutContent(book_id_int, order, new Date(),user_id);
		List<BookVol> vols =  new ArrayList<BookVol>();
		String update_time="";
		
		for(ConChapter conVol:list){
			BookVol vol = new BookVol();
			vol.setVol_id(conVol.getVol_id());
			vol.setVol_title(conVol.getVol_title());
			for(ConChapter conChapter:conVol.getChapters()){
				BookChapter chapter = new BookChapter();
				chapter.setChap_id(conChapter.getChap_id());
				chapter.setChap_name(conChapter.getChap_name());
				chapter.setChap_rank(conChapter.getChap_rank());
				chapter.setRelease_time(DateUtil.getString(conChapter.getRelease_time(), "MM-dd"));
				if(conChapter.getVip_status()!=0){
					chapter.setVip_status("VIP");
					if(conChapter.getUser_id()!=null){
						chapter.setIs_order("已订阅");
					}else
						chapter.setIs_order("");
					if(usSubscribe!=null){
						chapter.setIs_order("已订阅");
					}
				}else{
					chapter.setVip_status("");
				}
				if(conBook.getVip_status()==0){
					chapter.setVip_status("");
					chapter.setIs_order("");
				}
				
				vol.getChapters().add(chapter);
				update_time=chapter.getRelease_time();
			}
			vols.add(vol);
			
		}
		tokenMap.put("code", 200);
		tokenMap.put("auther_name", conBook.getAuthor_name());
		tokenMap.put("release_time",update_time);
		tokenMap.put("auther_id", conBook.getAuthor_id());
		tokenMap.put("content",vols);
		return IReadUtils.beanToJson(tokenMap); 
		
	}
	@Override
	public String updateChapterContent(int book_id1,int chapter_id,String token,String device_identifier) throws Exception {
		Map<String,Object> tokenMap = new HashMap<String,Object>();
		ConChapter conChapter = conChapterMapper.getChapterAndBookInfoById(chapter_id, new Date());
		/*ConBook book = conBookMapper.getBookById(book_id);
		
		if(book==null){
			tokenMap.put("code", 403);
			tokenMap.put("reason","图书不存在");
			return IReadUtils.beanToJson(tokenMap); 
		}
		
		*/
		if(null == conChapter){
			tokenMap.put("code", 403);
			tokenMap.put("reason","章节不存在");
			return IReadUtils.beanToJson(tokenMap); 
		}
		if(conChapter.getBook_status()!=1){
			tokenMap.put("code", 403);
			tokenMap.put("reason","图书已下架/不存在");
			return IReadUtils.beanToJson(tokenMap); 
		}
		if(conChapter.getStatus()!=1){
			tokenMap.put("code", 403);
			tokenMap.put("reason","章节已删除");
			return IReadUtils.beanToJson(tokenMap); 
		}
		String userId = IReadUtils.getUserIdByToken(token, ireadMemcacheService,device_identifier);
		if(conChapter.getVip_status()==0||conChapter.getBook_vip_status()==0){
			return updategetContent(conChapter.getBook_id(), chapter_id, conChapter.getChap_name(),conChapter.getChap_rank(),conChapter,userId);
		}
		
		if(StringUtils.isNullOrEmpty(userId)){
			tokenMap.put("code",302);
			//需要登录
			//进入系统登录页
			Map<String,Object> map = new HashMap<String,Object>();
			//系统登录
			map.put("redirect_rul", IReadContent.php_host+"user/login");
			map.put("errorMsg", "qsLogin");
			
			
			
			
			
			
			
			
			tokenMap.put("content", map);
			return IReadUtils.beanToJson(tokenMap);
		}
		
		//获取是否自动订购
		UsUser usUser = userMapper.getCustomUserInfoByUserid(Long.valueOf(userId), conChapter.getBook_id());
		//UsSubscribeAuto usSubscribeAuto = usSubscribeAutoMapper.getUsSubscribeById(Long.valueOf(userId),book_id);
		//
		if(usUser!=null){
			if(usUser.getUser_id().equals(conChapter.getAuthor_id()))
				return updategetContent(conChapter.getBook_id(), chapter_id, conChapter.getChap_name(), conChapter.getChap_rank(),conChapter,userId);
			UsSubscribe usSubscribe = null;
			//if(conChapter.getBook_vip_status()==2){
			//判断是否已订购
			usSubscribe = usSubscribeMapper.getUsSubscribeById(usUser.getUser_id(), conChapter.getBook_id(),0);
			if(usSubscribe==null){
				usSubscribe = usSubscribeMapper.getUsSubscribeById(usUser.getUser_id(),conChapter.getBook_id(), chapter_id);
		}
		//	}else{
				//判断是否已订购
			//	usSubscribe = usSubscribeMapper.getUsSubscribeById(usUser.getUser_id(), chapter_id);
		//	}
			
			if(usSubscribe==null){
				int temp=0;
				int fee = IReadUtils.getChapterFeeByUser(ireadMemcacheService, (long) usUser.getPoint(), userGradeMapper, conChapter.getWord_size(),conChapter);
				if(fee<=usUser.getBalance()){
					//自动订购
					if(usUser.getSubscribe_status()==1){
						try {
							addOrder(conChapter, usUser, fee);
							temp=1;
						} catch (Exception e) {
							temp=0;
							e.printStackTrace();
						}
					}
				}
				
				
				if(temp==0){
					tokenMap.put("code",302);
					Map<String,Object> map = new HashMap<String,Object>();
					//支付订单
					map.put("errorMsg", "qsOrder");
					map.put("chapter_name", conChapter.getChap_name());
					map.put("order_type", conChapter.getBook_vip_status());
					map.put("chapter_id", conChapter.getChap_id());
					map.put("vol_title", conChapter.getVol_title());
					map.put("book_name", conChapter.getBook_name());
					map.put("balance", usUser.getBalance());
					map.put("fee", fee);
					map.put("orderUrl", IReadContent.php_host+"subscribe/confirmed?cid="+chapter_id);
					
					
					
					map.put("preChapterId",0);
					map.put("nextChapterId",0);
					int preRemark = conChapter.getChap_rank()-1;
					if(preRemark<0){
						preRemark=0;
					}
					int nextRemark = conChapter.getChap_rank()+1;
					
					List<ConChapter> chapters = conChapterMapper.getBookChaptersByBookidAndPreRemark(conChapter.getBook_id(),preRemark,conChapter.getVol_id());
					if(chapters!=null){
						for(ConChapter chapter:chapters){
							map.put("preChapterId",chapter.getChap_id());
						}
					}
					chapters = conChapterMapper.getBookChaptersByBookidAndNextRemark(conChapter.getBook_id(),nextRemark,new Date(),conChapter.getVol_id());
					if(chapters!=null){
						for(ConChapter chapter:chapters){
							map.put("nextChapterId",chapter.getChap_id());
						}
					}
					
					ConChapter chapterContent = conChapterMapper.getChapterContentById(chapter_id);
					if(null!=chapterContent){
						String contentStr = chapterContent.getContent();
						if(contentStr.length()>200){
							map.put("content",contentStr.substring(0,200));
						}else{
							map.put("content",contentStr);
						}
						map.put("author_words", chapterContent.getAuthor_words());
					}
					
					
					
					
					
					
					
					tokenMap.put("content", map);
					return IReadUtils.beanToJson(tokenMap);
				}
			}
			
		}else{
			tokenMap.put("code", 403);
			tokenMap.put("reason","用户不存在");
			return IReadUtils.beanToJson(tokenMap); 
		}
		return updategetContent(conChapter.getBook_id(), chapter_id, conChapter.getChap_name(), conChapter.getChap_rank(),conChapter,userId);
	}
	private void addOrder(ConChapter conChapter,UsUser usUser,int fee) throws Exception{
		//添加订购记录
		UsSubscribe usSubscribe = new UsSubscribe();
		usSubscribe.setBook_id(conChapter.getBook_id());
		if(conChapter.getBook_vip_status()==2){
			usSubscribe.setChap_id(0);
			usSubscribe.setCharge_type(2);
		}else{
			usSubscribe.setChap_id(conChapter.getChap_id());
			usSubscribe.setCharge_type(1);
		}
		
		usSubscribe.setUser_id(usUser.getUser_id());
		usSubscribe.setCharge_fee(fee);
		
		int ret = usSubscribeMapper.addBookSubscribe(usSubscribe);
		if(ret == 1){
			UsBalance usBalance = new UsBalance();
			usBalance.setBalance(fee);
			usBalance.setNum(fee);
			usBalance.setVersion(usUser.getBalance_version());
			usBalance.setUser_id(usUser.getUser_id());
			//更新余额
			ret = usBalanceMapper.updateBalanceByorder(usBalance);
			if(ret == 0){
				for(int i=0;i<10;i++){
					UsBalance base = usBalanceMapper.getBalance(usUser.getUser_id());
					usBalance = new UsBalance();
					usBalance.setBalance(fee);
					usBalance.setNum(fee);
					usBalance.setVersion(base.getVersion());
					usBalance.setUser_id(base.getUser_id());
					ret = usBalanceMapper.updateBalanceByorder(usBalance);
					if(ret==1){
						break;
					}
				}
			}
			if(ret ==0){
				throw new Exception("扣除余额异常");
			}else{
				ConBookStat conBookStat = conBookStatMapper.getBookStatById(conChapter.getBook_id());
				if(!updateDataService.updateConBookStat(conBookStat, conChapter.getBook_id(), 5, 1,null,fee))
					throw new Exception("更新订单数量异常");
			}
			try {
				if(conChapter.getBook_vip_status()==2){
					usConsumeMapper.addUsConsume(usUser.getUser_id(), conChapter.getBook_id(), conChapter.getChap_id(),conChapter.getBook_name()+"-全本" , fee, 2);

				}else{
					usConsumeMapper.addUsConsume(usUser.getUser_id(), conChapter.getBook_id(), conChapter.getChap_id(),conChapter.getBook_name()+"-"+ conChapter.getChap_name(), fee, 1);

				}
			} catch (Exception e) {
				Map<String,Object> errorJson = new HashMap<String, Object>();
				errorJson.put("user_id", usUser.getUser_id());
				errorJson.put("book_id", conChapter.getBook_id());
				errorJson.put("chapter_id", conChapter.getChap_id());
				errorJson.put("fee", fee);
				errorJson.put("type", 1);
				QSReadException.printf(e, "创建消费记录异常");
			}
			try {
				UsMemberPoint usMemberPoint =usMemberPointMapper.getPoint(usUser.getUser_id());
				if(usMemberPoint!=null){
					int consume_fee =usMemberPoint.getConsume_fee()+fee;
					usMemberPoint.setConsume_fee(consume_fee%50);
					usMemberPoint.setPoint(usMemberPoint.getPoint()+consume_fee/50);
				}
				updateDataService.updateMemberPoint(usMemberPoint,fee,0,usUser.getUser_id());
			} catch (Exception e) {
				Map<String,Object> errorJson = new HashMap<String, Object>();
				errorJson.put("user_id", usUser.getUser_id());
				errorJson.put("book_id", conChapter.getBook_id());
				errorJson.put("chapter_id", conChapter.getChap_id());
				errorJson.put("fee", fee);
				errorJson.put("type", 1);
				QSReadException.printf(e, "创建消费记录异常");
			}
			String log = conChapter.getBook_id()+"|"+conChapter.getChap_id()+"|"+fee+"|"+usUser.getUser_id();
			CustomerLog.orderLog(logger, log);
				
		}
	}
	private String updategetContent(int book_id,int chapter_id,String name,int remark,ConChapter conChapter,String user_id){
		Map<String,Object> tokenMap = new HashMap<String,Object>();
		tokenMap.put("code",200);
		BookChapterContent content = new BookChapterContent();
		content.setPreChapterId(0);
		content.setNextChapterId(0);
		int preRemark = Integer.valueOf(remark)-1;
		if(preRemark<0){
			preRemark=0;
		}
		int nextRemark = Integer.valueOf(remark)+1;
		
		List<ConChapter> chapters = conChapterMapper.getBookChaptersByBookidAndPreRemark(book_id,preRemark,conChapter.getVol_id());
		if(chapters!=null){
			for(ConChapter chapter:chapters){
				content.setPreChapterId(chapter.getChap_id());
			}
		}
		chapters = conChapterMapper.getBookChaptersByBookidAndNextRemark(book_id,nextRemark,new Date(),conChapter.getVol_id());
		if(chapters!=null){
			for(ConChapter chapter:chapters){
				content.setNextChapterId(chapter.getChap_id());
			}
		}
		ConChapter chapterContent = conChapterMapper.getChapterContentById(chapter_id);
		if(null!=chapterContent){
			content.setContent(chapterContent.getContent());
			content.setAuthor_words(chapterContent.getAuthor_words());
		}
		content.setAuthor_name(conChapter.getAuthor_name());
		content.setAuthor_id(conChapter.getAuthor_id()+"");
		content.setReviews_num( usBookReviewMapper.getBookReviewCountByList(book_id, 1, 0,chapter_id));
		content.setRelease_time(DateUtil.getString(conChapter.getRelease_time(), "yyyy-MM-dd HH:mm:ss"));
		content.setWord_size(conChapter.getWord_size());
		if(!StringUtils.isNullOrEmpty(name)){
			content.setName(name);
		}
		content.setChap_reviews(conChapter.getChap_reviews());
		tokenMap.put("content", content);
		
		ConBookStat conBookStat = conBookStatMapper.getBookStatById(book_id);
		try {
			updateDataService.updateConBookStat(conBookStat, book_id, 6,1,null,0);
		} catch (Exception e1) {
			QSReadException.printf(e1, "统计异常");
		}
		if(!StringUtils.isNullOrEmpty(user_id)){
			UsBookRecent usBookRecent = new UsBookRecent();
			usBookRecent.setUser_id(Long.valueOf(user_id));
			usBookRecent.setBook_id(book_id);
		
			usBookRecent.setChapter_id(chapter_id);
			usBookRecent.setChapter_name(name);
			UsBookShelf usBookShelf = usBookShelfMapper.getShelfByBookIdAndUserId(book_id,Long.valueOf(user_id));
			if(usBookShelf!=null){
				usBookShelf.setChap_id(chapter_id);
			}
			try {
				UpdateTask updateTask = new UpdateTask(1, usBookRecent,usBookRecentMapper);
				updateTask.run();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		String log = conChapter.getBook_id()+"|"+conChapter.getChap_id()+"|"+"|"+user_id;
		CustomerLog.readLog(logger, log);
		return IReadUtils.beanToJson(tokenMap);
	}

	@Override
	public String getChapterList(String book_id, int pages, int contents,
			String order,String token,String device_identifier) {
		Map<String,Object> tokenMap = new HashMap<String,Object>();
		int book_id_int=0;
		try {
			
			book_id_int = Integer.valueOf(book_id);
		} catch (NumberFormatException e) {
			book_id_int=0;
		}
		if(book_id_int<=0||pages<=0||contents<=0){
			tokenMap.put("code", 403);
			tokenMap.put("reason","参数错误");
			return IReadUtils.beanToJson(tokenMap); 
		}
		if(StringUtils.isNullOrEmpty(order)){
			order = "asc";
		}else if("desc".equals(order.toLowerCase())){
				order = "desc";
		}
		String user_id = IReadUtils.getUserIdByToken(token, ireadMemcacheService, device_identifier);
		UsSubscribe usSubscribe = null;
		if(StringUtils.isNullOrEmpty(user_id)){
			user_id=null;
		}else{
			//判断是否已订购
			usSubscribe = usSubscribeMapper.getUsSubscribeById(Long.valueOf(user_id),book_id_int, 0);
		}
		int index=(pages-1)*contents;
		int total = conChapterMapper.getChaptersCountWithoutContent(book_id_int, new Date());
		tokenMap.put("total", total);
		ConBook conBook = conBookMapper.getBookById(book_id_int);
		List<ConChapter> list = conChapterMapper.getChapterListWithoutContent(book_id_int, index, contents, order, new Date(),user_id);
		List<Chapter> cps = new ArrayList<Chapter>();
		for(ConChapter conChapter:list){
			Chapter chapter = new Chapter();
			chapter.setChap_id(conChapter.getChap_id());
			chapter.setChap_name(conChapter.getChap_name());
			chapter.setChap_rank(conChapter.getChap_rank());
			chapter.setVol_title(conChapter.getVol_title());
			
			if(conChapter.getVip_status()!=0){
				chapter.setVip_status("VIP");
				if(conChapter.getUser_id()!=null){
					chapter.setIs_order("已订阅");
				}else
					chapter.setIs_order("");
				if(usSubscribe!=null){
					chapter.setIs_order("已订阅");
				}
			}else{
				chapter.setVip_status("");
			}
			if(conBook.getVip_status()==0){
				chapter.setVip_status("");
				chapter.setIs_order("");
			}
			cps.add(chapter);
		}
		tokenMap.put("code", 200);
		tokenMap.put("content",cps);
		return IReadUtils.beanToJson(tokenMap);
	}
	@Override
	public String updateBookAuto(int book_id, int status, String token,
			String device_identifier) {
		Map<String,Object> tokenMap = new HashMap<String,Object>();
		String user_id = IReadUtils.getUserIdByToken(token, ireadMemcacheService, device_identifier);
		if(StringUtils.isNullOrEmpty(user_id)){
			tokenMap.put("code", 403);
			tokenMap.put("reason","用户未登陆");
			return IReadUtils.beanToJson(tokenMap); 
		}
		UsSubscribeAuto usSubscribeAuto = new UsSubscribeAuto();
		usSubscribeAuto.setUser_id(Long.valueOf(user_id));
		usSubscribeAuto.setStatus(status);
		usSubscribeAuto.setBook_id(book_id);
		usSubscribeAutoMapper.updateBookAuto(usSubscribeAuto);
		
		tokenMap.put("code", 200);
		if(status==1){
			tokenMap.put("content","设置自动订购成功");
		}else{
			tokenMap.put("content","取消自动订购成功");
		}
		
		return IReadUtils.beanToJson(tokenMap); 
	}
	@Override
	public String updateOrderPay(int chapter_id, String token,
			String device_identifier) throws Exception {
		Map<String,Object> tokenMap = new HashMap<String,Object>();
		ConChapter conChapter = conChapterMapper.getChapterAndBookInfoById(chapter_id, new Date());
		if(null == conChapter){
			tokenMap.put("code", 403);
			tokenMap.put("reason","章节不存在");
			return IReadUtils.beanToJson(tokenMap); 
		}
		if(conChapter.getBook_status()!=1){
			tokenMap.put("code", 403);
			tokenMap.put("reason","图书已下架/不存在");
			return IReadUtils.beanToJson(tokenMap); 
		}
		if(conChapter.getStatus()!=1){
			tokenMap.put("code", 403);
			tokenMap.put("reason","章节已删除");
			return IReadUtils.beanToJson(tokenMap); 
		}
		if(conChapter.getVip_status()==0){
			tokenMap.put("code", 200);
			tokenMap.put("content","支付成功");
			return IReadUtils.beanToJson(tokenMap); 
		}
		String userId = IReadUtils.getUserIdByToken(token, ireadMemcacheService,device_identifier);
		if(StringUtils.isNullOrEmpty(userId)){
			tokenMap.put("code",302);
			//需要登录
			//进入系统登录页
			Map<String,Object> map = new HashMap<String,Object>();
			//系统登录
			map.put("redirect_rul", IReadContent.php_host+"user/login");
			map.put("errorMsg", "qsLogin");
			tokenMap.put("content", map);
			return IReadUtils.beanToJson(tokenMap);
		}
		
		//获取用户
		UsUser usUser = userMapper.getCustomUserInfoByUserid(Long.valueOf(userId), conChapter.getBook_id());
		//UsSubscribeAuto usSubscribeAuto = usSubscribeAutoMapper.getUsSubscribeById(Long.valueOf(userId),book_id);
		//
		if(usUser!=null){
			int fee = IReadUtils.getChapterFeeByUser(ireadMemcacheService, (long) usUser.getPoint(), userGradeMapper, conChapter.getWord_size(),conChapter);
			if(fee>usUser.getBalance()){
				tokenMap.put("code", 403);
				tokenMap.put("reason","余额不足");
				return IReadUtils.beanToJson(tokenMap); 
			}
			UsSubscribe usSubscribe=null;
			if(conChapter.getBook_vip_status()==2){
				//判断是否已订购
				usSubscribe = usSubscribeMapper.getUsSubscribeById(usUser.getUser_id(), conChapter.getBook_id(),0);
			}else{
				//判断是否已订购
				usSubscribe = usSubscribeMapper.getUsSubscribeById(usUser.getUser_id(), conChapter.getBook_id(),chapter_id);
			}
			if(usSubscribe==null){
				//订购
				addOrder(conChapter, usUser, fee);
			}
		}else{
			tokenMap.put("code", 403);
			tokenMap.put("reason","用户不存在");
			return IReadUtils.beanToJson(tokenMap); 
		}
		tokenMap.put("code", 200);
		tokenMap.put("content","支付成功");
		return IReadUtils.beanToJson(tokenMap); 
	}
	@Override
	public String addRewardBook(int book_id, int num, String token,
			String device_identifier) throws Exception {
		Map<String,Object> tokenMap = new HashMap<String,Object>();
		if(book_id<=0||num<=0){
			tokenMap.put("code", 403);
			tokenMap.put("reason","参数错误");
			return IReadUtils.beanToJson(tokenMap);
		}
		String user_id  = IReadUtils.getUserIdByToken(token, ireadMemcacheService, device_identifier);
		if(StringUtils.isNullOrEmpty(user_id)){
			tokenMap.put("code", 403);
			tokenMap.put("reason","用户未登录");
			return IReadUtils.beanToJson(tokenMap);
		}
		ConBook conBook = conBookMapper.getBookById(book_id);
		if(null==conBook){
			tokenMap.put("code", 403);
			tokenMap.put("reason","书籍已下架");
			return IReadUtils.beanToJson(tokenMap);
		}
		for(int i=0;i<10;i++){
			UsBalance usBalance = usBalanceMapper.getBalance(Long.valueOf(user_id));
			if(num<usBalance.getBalance()){
				usBalance.setNum(num);
				int ret = usBalanceMapper.updateBalanceByorder(usBalance);
				if(ret == 1){
					ConBookStat conBookStat = conBookStatMapper.getBookStatById(book_id);
					if(updateDataService.updateConBookStat(conBookStat, book_id, 3,num,null,0)){
						int temp=usConsumeMapper.addUsConsume(Long.valueOf(user_id), book_id,0,"打赏《"+conBook.getBook_name()+"》", num, 3);
						if(temp!=1){
							throw new Exception("打赏异常");
						}else{
							UsMemberPoint usMemberPoint = usMemberPointMapper.getPoint(Long.valueOf(user_id));
							if(usMemberPoint!=null){
								int consume_fee =usMemberPoint.getConsume_fee()+num;
								usMemberPoint.setConsume_fee(consume_fee%50);
								usMemberPoint.setPoint(usMemberPoint.getPoint()+consume_fee/50);
							}
							updateDataService.updateMemberPoint(usMemberPoint,num,0,Long.valueOf(user_id));
						}
					}
					break;
				}
			}else{
				tokenMap.put("code", 9910);
				tokenMap.put("reason","余额不足");
				return IReadUtils.beanToJson(tokenMap);
			}
		}
		
		
		
		
		tokenMap.put("code", 200);
		tokenMap.put("content","打赏成功");
		return IReadUtils.beanToJson(tokenMap);
	}
	@Override
	public String updatePresentVotes(int book_id, int num, String token,
			String device_identifier) throws Exception {
		Map<String,Object> tokenMap = new HashMap<String,Object>();
		if(book_id<=0||num<=0){
			tokenMap.put("code", 403);
			tokenMap.put("reason","参数错误");
			return IReadUtils.beanToJson(tokenMap);
		}
		String user_id  = IReadUtils.getUserIdByToken(token, ireadMemcacheService, device_identifier);
		if(StringUtils.isNullOrEmpty(user_id)){
			tokenMap.put("code", 403);
			tokenMap.put("reason","用户未登录");
			return IReadUtils.beanToJson(tokenMap);
		}
		ConBook conBook = conBookMapper.getBookById(book_id);
		if(null==conBook){
			tokenMap.put("code", 403);
			tokenMap.put("reason","书籍已下架");
			return IReadUtils.beanToJson(tokenMap);
		}
		UsUser usUser = userMapper.getCustomUserByUserid(Long.valueOf(user_id));
		if(usUser!=null){
			int total_votes = IReadUtils.getTotalVotes((long) usUser.getPoint(), ireadMemcacheService, userGradeMapper);
			String date = DateUtil.getString(new Date(), "yyyyMMdd");
			UsMemberVotes usMemberVotes = usMemberVotesMapper.getVotes(Long.valueOf(user_id),Integer.valueOf(date));
			int is_new=1;//数据库是否存在
			if(null==usMemberVotes){
				usMemberVotes = new UsMemberVotes();
				usMemberVotes.setStat_day(Integer.valueOf(date));
				usMemberVotes.setUser_id(Long.valueOf(user_id));
				usMemberVotes.setUsed_votes(num);
				usMemberVotes.setTotal_votes(total_votes);
				if(num>total_votes){
					tokenMap.put("code", 403);
					tokenMap.put("reason","客官,红票已经用完,试试打赏呗!");
					return IReadUtils.beanToJson(tokenMap);
				}
				is_new=0;
			}else{
				if(num>total_votes-usMemberVotes.getUsed_votes()){
					tokenMap.put("code", 403);
					tokenMap.put("reason","客官,红票已经用完,试试打赏呗!");
					return IReadUtils.beanToJson(tokenMap);
				}
			}
			int ret= 0;
			try{
				if(is_new==0){
					 ret = usMemberVotesMapper.addVotes(usMemberVotes);
				}
			}catch(Exception e){
				QSReadException.printf(e,"");
				usMemberVotes = usMemberVotesMapper.getVotes(Long.valueOf(user_id),Integer.valueOf(date));
				if(num>total_votes-usMemberVotes.getUsed_votes()){
					tokenMap.put("code", 403);
					tokenMap.put("reason","客官,红票已经用完,试试打赏呗!");
					return IReadUtils.beanToJson(tokenMap);
				}
			}
			if(ret ==0){
				usMemberVotes.setNum(num);
				for(int i=0;i<10;i++){
					ret = usMemberVotesMapper.updateVotes(usMemberVotes);
					if(ret == 1){
						break;
					}
					usMemberVotes = usMemberVotesMapper.getVotes(Long.valueOf(user_id),Integer.valueOf(date));
					if(num>total_votes-usMemberVotes.getUsed_votes()){
						tokenMap.put("code", 403);
						tokenMap.put("reason","客官,红票已经用完,试试打赏呗!");
						return IReadUtils.beanToJson(tokenMap);
					}
					usMemberVotes.setNum(num);
				}
			}
			if(ret == 1){
				ConBookStat conBookStat = conBookStatMapper.getBookStatById(book_id);
				if(!updateDataService.updateConBookStat(conBookStat, book_id, 2,0,null,0)){
					throw new Exception("赠送异常");
				/*	int temp=usConsumeMapper.addUsConsume(Long.valueOf(user_id), book_id,0,"赠送《"+conBook.getAuthor_name()+"》金票", num, 4);
					if(temp!=1){
						throw new Exception("赠送异常");
					}*/
				}
			}
			
		}
		
		
		tokenMap.put("code", 200);
		tokenMap.put("content","赠送成功");
		return IReadUtils.beanToJson(tokenMap);
	}
	@Override
	public String getBookRewardList(int book_id,int pages, int contents) {
		if(pages==0)
			pages=1;
		if(contents==0)
			contents=20;
		int index = (pages-1)*contents;
		List<UsConsume> usConsumes = usConsumeMapper.getUsConsumeListByParam(null, book_id, 3, null, null, index, contents);
		PageData<Consume> page = new PageData<Consume>();
		List<Consume> consumes = new ArrayList<Consume>();
		for(UsConsume usConsume:usConsumes){
			Consume consume = new Consume();
			consume.setId(usConsume.getId()+"");
			consume.setConsume_fee(usConsume.getConsume_fee());
			consume.setAuthor_id(usConsume.getAuthor_id()+"");
			if(usConsume.getConsume_type()==1){
				consume.setConsume_type("按章订购");
			}else if(usConsume.getConsume_type()==2){
				consume.setConsume_type("按本订购");
			}if(usConsume.getConsume_type()==3){
				consume.setConsume_type("打赏");
			}if(usConsume.getConsume_type()==4){
				consume.setConsume_type("月票");
			}
			consume.setContent_id(usConsume.getUser_id()+"");
			consume.setContent_name(usConsume.getUser_name());
			if(!StringUtils.isNullOrEmpty(usConsume.getImage_url()))
				consume.setImage_url(IReadContent.portrait_url+usConsume.getImage_url());
/*			consume.setContent_id(usConsume.getContent_id());
			consume.setContent_name(usConsume.getContent_name());
*/			consume.setCreate_time(DateUtil.getString(usConsume.getCreate_time(), "yyyy-MM-dd HH:mm:ss"));
			consumes.add(consume);
		}
		page.setContent(consumes);
		page.setCode(200);
		page.setPageNumber(pages);
		page.setPageSize(contents);
		page.setTotal( usConsumeMapper.getUsConsumeListCountByParam(null, book_id, 3, null,null));
		return IReadUtils.beanToJson(page); 
	}
}
